package com.xiaoshuidi.cloud.module.rooms.mq.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.fastjson.JSON;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomequipment.vo.PartLeaseEquipmentTemplateVo;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomequipment.vo.WholeLeaseEquipmentTemplateVo;
import com.xiaoshuidi.cloud.module.rooms.service.RoomEquipmentService;
import com.xiaoshuidi.cloud.module.rooms.valid.WholeLeaseEquipmentImportValid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@AllArgsConstructor
public class WholeLeaseEquipmentListener extends AbstractExcelListener<WholeLeaseEquipmentTemplateVo>{
    private Long apartmentId;
    private Long tenantId;

    private Long userId;
    private AtomicInteger count;

    private RoomEquipmentService roomEquipmentService;


    @Override
    public void invoke(WholeLeaseEquipmentTemplateVo data, AnalysisContext context) {
        count.incrementAndGet();
        log.info("wholeEquipment解析到一条数据:{}", JSON.toJSONString(data));
         WholeLeaseEquipmentImportValid wholeLeaseEquipmentImportValid = new WholeLeaseEquipmentImportValid();
        boolean valid = true;
        HashMap<String, String> errorMap = new HashMap<>();
        try {
            valid = wholeLeaseEquipmentImportValid.valid(data, errorMap);
        } catch (Exception e) {
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "集中式第" + count + "行" + e.getMessage());
        }
        if (!valid) {
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "集中式第" + count + "行" + JSON.toJSONString(errorMap.values()));
        }
        cachedDataList.add(data);
    }

    @Override
    public void saveData() {
        if (this.cachedDataList.size() > 0) {
            //保存数据
            List<PartLeaseEquipmentTemplateVo> equipments = this.cachedDataList.stream().map(r -> {
                PartLeaseEquipmentTemplateVo vo = new PartLeaseEquipmentTemplateVo();
                        BeanUtils.copyProperties(r, vo);
                        return vo;
                    }
            ).collect(Collectors.toList());
            try {
                roomEquipmentService.batchImportEquipment(equipments,apartmentId,tenantId,userId,"whole");
            } catch (Exception e) {
                throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
            }
        }
    }
}
